<?php
/**
 * Atlas KOTASOFT cakephp
 *
 * Bakes web interface 
 *
 * PHP versions 4 and 5
 *
 * ATLAS KOTASOFT  cakephp web code generator
 * Copyright 2009, Kotasoft agile factory, Inc. (http://www.atlascakephp.com)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2009, Kotasoft agile factory , Inc. (http://www.kotasoft.com)
 * @link          http://www.atlascakephp.com  ATLAS KOTASOFT Project
 * @version       BETA 0.5 $
 * @modifiedby    $LastChangedBy: daniel castanera - guldoe and francisco dominguez - idioto $
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */

require ("kt_app_controller.php");

/* class KtcontrollersController, generate controllers */
class KtcontrollersController extends KtAppController {			
 	var $ruta_admin = "/admin/ktcontrollers/"; 	 
 	var $components = array('json');
 	
 	/* index for admin, get tables from database */
	function admin_index(){	  
	  $session=$this->Session->read(KT_SESSION); 
 	  $this->set("configuration",$session['Ktconfiguration']);      
	  // select bd configuration 
	  if(!$this->__dbConfig()){
	       $this->Session->setFlash(__('Your configuration is not available',true));		 	
	  }
		
	  if (!empty($this->data)) {	  	 
			$this->userDbConfig=$this->data['Ktcontroller']['selectedbd'];
	  }else if (count($session['Ktconfiguration'])>0){      
	  		$this->userDbConfig = $session['Ktconfiguration']['name'];
        
	  }	
	  
	  $useDbConfig=$this->userDbConfig;
	  if ($useDbConfig!=""){
					$this->set('configName',$this->data['Ktcontroller']['selectedbd']);	   
					$this->set('ruta_admin',$this->ruta_admin);	 
					
					$tables=$this->listAll($useDbConfig);
					$tables_model	=$this->__tables_with_model($tables);	
					$tables_no_model=$this->__tables_without_model($tables);	
					
					if(count($tables_model)> 0)		$this->set('tables', $tables_model); 		
					else							$this->set('tables', array()); 	
					if(count($tables_no_model)>0)	$this->set('tables_no_model',$tables_no_model);	
					else							$this->set('tables_no_model',array());	
					  
		    		//$this->__getModelsBd();
	  } else {
				$this->Session->setFlash(__('Your database not have tables available',true));
				$this->log(__('Your database not have tables available',true), LOG_DEBUG);	
		}
     }
	 
     
    /* render file */ 
	function admin_norender($names=null) {
		$session=$this->Session->read(KT_SESSION); 			
		$this->userDbConfig=$session['Ktconfiguration']["name"]; 		 
		
		$this->layout ='print_layout';
	    
	    //  check directory
	    $mensaje = $this->__checkDirectory();	
	        
	    if ($mensaje!=""){
	    	$this->Session->setFlash(__($mensaje,true));	
	    	$this->redirect(array('action' => 'admin_index'));
	    }
	    
		if (!empty($this->data)) { 
	  	  $this->controllerName=$this->data["Ktcontroller"]["names"];	  	
	  	  $currentControllerName = $this->_modelName($this->controllerName);
		  $pluralModelName =$this->_pluralName($currentControllerName);
		  $singularName = Inflector::variable($currentControllerName);
		  
		  $nameClass = Inflector::humanize($pluralModelName);
	  	  
	  	  $this->set("currentControllerName",$currentControllerName);
		  $this->set("pluralName",$pluralModelName);	
		   
		  $this->set("className",$nameClass);
		  $this->set("modelName",$currentControllerName);
		  $this->set("pluralModelName",$pluralModelName);		  
		  $this->set("singularModelName",$singularName);
		  
		  
		  
		  $options = $this->data['Ktcontroller'];
	  	 
	   	  // check helpers
	  	  if ($options['helpers']['info'] != false) { 
	  	  	 $this->set("helpers",$this->__createHelpers());
	  	  }	  	  
	  	  // check components
	  	  if ($options['components']['info'] != false) {  
	  	  	 $this->set("components",$this->__createComponents());	  	  
	  	  }	  	  
		   
	  	  $control = $this->__createSelectors();	  	  
	  	  $this->set("selectors",$control["selector"]);	  	  
	  	  $this->set("uses",$control["uses"]);	

	  	  // check paginator
	  	  if($options['paginator']['nelements']!="" || $options['paginator']['order']!=""){	  	  	
	  	  		 $this->set("paginator",$this->__createPaginator());	  	 
	  	  }
	  	  
	  	  
	  	  // check function index
	  	  if ($options['usercheck']['index'] != false) { 
	  	  	  $this->set("index","true");	  	  	
	  	  }

	  	  // check function view
	  	  if ($options['usercheck']['view'] != false) { 	  
	  	  	  $this->set("view","true");
	  	  }
	  	  
	  	  // check function add
	  	  if ($options['usercheck']['add'] != false) {    	  
	  	  	   $this->set("add","true");
	  	  }
	  	  
	  	  // check function edit
	  	  if ($options['usercheck']['edit'] != false) { 	  
	  	    $this->set("edit","true");
	  	  }
	  	  
	  	  // check function delete
	  	  if ($options['usercheck']['del'] != false) {   	  
	  	  	  $this->set("del","true");
	  	  }
	  	  
	  	  // check function index for admin
	  	  if ($options['admincheck']['index'] != false) { 	  
	  	  	  $this->set("adminIndex","true");
	  	  }
	  	  
	  	  // check function view for admin
	  	  if ($options['admincheck']['view'] != false) { 
	  	  	  $this->set("adminView","true");
	  	  }
	  	  
	  	  // check function add for admin
	  	  if ($options['admincheck']['add'] != false) { 
	  	  	  $this->set("adminAdd","true");
	  	  }
	  	  
	  	  // check function edit for admin
	  	  if ($options['admincheck']['edit'] != false) {  
	  	 	   $this->set("adminEdit","true");
	  	  }
	  	  
	  	  // check function del for admin
	  	  if ($options['admincheck']['del'] != false) {  
	  	  	  $this->set("adminDel","true");
	  	  }
		  
	  	  
	  	  
	  	  
		 $this->set("userDbConfig",$this->userDbConfig);
		 
		 // TODO  refactor sessions & directories
	     $session = $this->Session->read(KT_SESSION);	      
		 $path = $session[KT_CONFIGURATION][KT_DIRECTORY]."/app/controllers".DS; 
		 $filename = $path . Inflector::underscore($pluralModelName) . '_controller.php'; 
		 $session=$this->Session->read(KT_SESSION); 			
		 $this->userDbConfig=$session['Ktconfiguration']["name"]; 	
	      
		 if($this->createFile($filename, $this->render())){		 	
				$this->Session->setFlash(__('ktcontroller_created',true));
				$this->log(__('ktcontroller_created',true), LOG_DEBUG);	
    			$this->redirect(array('action' => 'admin_index'));
		 }else{
				$this->Session->setFlash(__('kcontroller_nocreated',true));
				$this->log(__('kcontroller_nocreated',true), LOG_DEBUG);	
    			$this->redirect(array('action' => 'admin_index'));
		  }
		  
	    } // empty data
		 
	} // fin admin_norender 
	
	
	
	/*  admin generate, let you select configuration from a database you have been choose*/
	function admin_generate($names=null) {
		
		$this->set("name",$names);
		$session=$this->Session->read(KT_SESSION); 			
		$this->userDbConfig=$session['Ktconfiguration']["name"]; 	
	    $this->set("userDbConfig",$this->userDbConfig);
	    $session=$this->Session->read(KT_SESSION); 
 	    $this->set("configuration",$session['Ktconfiguration']); 
 	    
		//generate selector
 	    $this->__getListTables();
 	  
 	    // check configuration exists
 	    if ($names!=""){
 	    	if (file_exists($this->__getPath() . Inflector::underscore($names) .'_controller.php')) {
				$this->Session->setFlash(__('File exits you are going to overwrite it',true));
				$this->log(__('File exits you are going to overwrite it',true), LOG_DEBUG);		
			}
 	    }	
 	    
 	    if(!$this->__checkDirectoryProject()){
 	    		$this->Session->setFlash(__('Error directory configuration, files not could be created, check configuration',true));
 	    		$this->log(__('Error directory configuration, files not could be created, check configuration',true), LOG_DEBUG);
 	    		$this->redirect("/admin/ktconfigurations");	
 	    }    
	}	
	
	
    
    
    /* function add paginator */
    function __createPaginator(){
    	$output = "";
    	$paginatorInfo = $this->data["Ktcontroller"]["paginator"];
    	
    	$output .= "\tvar \$paginate = array(";
    	$output .= "\n\t\t '". $this->_modelName($this->data["Ktcontroller"]['names'])."' => array( ";
    	
    	if ($paginatorInfo["nelements"]!="" && is_numeric($paginatorInfo["nelements"])) {
    		$output .= "\n\t\t 'limit' => '".$paginatorInfo["nelements"]. "',";    		
    	} else {
    		$output .= "\n\t\t 'limit' => '10',";
    	}
    	$output .= "\n\t\t 'page' => '1',";
    	
    	if ($paginatorInfo["order"]!=""){
    		$output .= "\n\t\t 'order'    => array(";
    		$listOrder = split(",", $paginatorInfo["order"]);
    		foreach ($listOrder as $order) {
    			$output .= "'". $this->_modelName($this->data["Ktcontroller"]['names']).".".$order ."' => 'asc'";  
    		}
    		
    		$output .= "\n\t\t )";
    	}
    	
    	$output .= "\n\t\t ));";
    	return $output;
    }
    
	/* function add helpers */
	function __createHelpers(){
		$output="";
		$helpersList = $this->data["Ktcontroller"]['helpers']['info'];
		$helpersListTrimmed = str_replace(' ', '', $helpersList);
		$helpers = explode(',', $helpersListTrimmed);
		
		$output .= "\tvar \$helpers = array('Html', 'Form'";
			if (count($helpers)) {
				foreach ($helpers as $help) {
					$output .= ", '" . Inflector::camelize($help) . "'";
				}
			}
		$output .= ");\n";
		
		return $output; 
	}
	
	function __createSelectors(){
		
		$output =""; 
		
		$usesAux = "\tvar \$uses = array(";
		
		$cont=1;		
		$firstModel=true;
		//echo "<pre>"; print_r($this->data["Ktcontroller"]); echo "</pre>"; die();
		
		$usesAux .= "'".$this->_modelName($this->data["Ktcontroller"]['names'])."'";
		
		$selectorList = $this->data["Ktcontroller"]['selector'];
		foreach ($selectorList as $selector) {
		 if ($selector["model"]!="" && 
		 	 $selector["label"]!="" && 
		 	 $selector["value"]) {
		 	 		
		 	  $modelo = $this->_modelName($selector["model"]);
		 	  //$usesAux .="'".$selector["model"]."'";
		 	  //if ($firstModel=="true"){
		 	  	//$usesAux .="'".$modelo."'";
		 	  //	$firstModel=false;
		 	  //}else {
		 	  $firstModel=false;
		 	  $usesAux .= ", '".$modelo."'";
		 	 // }
		 	  $output .="\n\t\t  \$arrays= Array();";
			  //$output .= "\n\t\t  \$value = new ".$modelo."();";
			 // $output .="\n\t\t \$values= \$value->find('all');";		
			 // $output .="\n\t\t foreach (\$values as \$aux) {";
			 // $output .="\n\t\t \$arrays[\$aux['".$modelo."']['".$selector['value']."']]= \$aux['".$modelo."']['".$selector['label']."'];	";
			 // $output .="\n\t\t }";
			//  $output .="\n\t\t \$this->set('selector_info".$cont."',\$arrays);";		
			  $output .= "\n\t\t  \$this->loadModel('".$modelo."');";
			  $output .= "\n\t\t  \$values = \$this->".$modelo."->find('all');";				 
			  $output .= "\n\t\t  foreach (\$values as \$aux) {";	
			  $output .="\n\t\t \$arrays[\$aux['".$modelo."']['".$selector['value']."']]= \$aux['".$modelo."']['".$selector['label']."'];	";
		 	  $output .="\n\t\t }";
		 	  $output .="\n\t\t \$this->set('selector_info".$cont."',\$arrays);";		
			  $cont++;  
			  
			  
			  /*$arrays = Array();
		 $this->loadModel('Tipo');
		 $values = $this->Tipo->find('all');		 
		 foreach ($values as $aux) {
		 	$arrays[$aux['tipo']['id']]= $aux['tipo']['name'];	
		 }		 
		 $this->set('selector_tipo',$arrays);*/
			  
			  
		 }
		}
		
		
		$usesAux .= ");";
		$arrayResults["uses"] ="";	
		$arrayResults["selector"] =$output;
		if($firstModel==false){
			$arrayResults["uses"] = $usesAux;
		}
		return $arrayResults;
		
	}
	
	
	/* function add component */
	function __createComponents(){
		$output="";
		$componentsList = $this->data["Ktcontroller"]['components']['info'];
		$componentsListTrimmed = str_replace(' ', '', $componentsList);
		$components = explode(',', $componentsListTrimmed);
		
	    if (count($components)) {
				$output .= "\tvar \$components = array(";

				foreach ($components as $comp) {
					if ($comp != $components[count($components) - 1]) {
						$output .= "'" . Inflector::camelize($comp) . "', ";
					} else {
						$output .= "'" . Inflector::camelize($comp) . "'";
					}
				}
				$output .= ");\n";
			}
			
		return $output; 
	}
	
	/*return ajax of rows of a bd table*/
	function admin_getListRows($names=null){
		//$this->autoRender = false; 
		Configure::write('debug', 0);
		$rows=Array();
				
		$session=$this->Session->read(KT_SESSION); 			
		$this->userDbConfig=$session['Ktconfiguration']["name"]; 	
	   
 	    $rows=$this->__model_results($this->userDbConfig,$names); 		
		$this->set('rows', $rows); 
	}
	
	
	
     function __model_results($configName,$names){ 
     
      	$model = new Model("",$names,$configName);
      	if (!is_object($model)) {
			return false;
		}
		$fields = $model->schema();
      	
		foreach ($fields as $field => $value){	
		          $array[$field]= $field;		
		}
		
      	return $array;        
      }
	
	
	
	
	/* get list of tables bd*/
    function __getListTables() {
    	 
		$useDbConfig = $this->userDbConfig;
		$configs = get_class_vars('DATABASE_CONFIG');

		if (!is_array($configs)) {
			return $this->DbConfig->execute();
		}
		  
        $db =& ConnectionManager::getDataSource($useDbConfig); 
		$tables = $db->listSources();
		$arrayTables= Array();
		
		foreach ($tables as $table){
			$singular = $this->_modelName($table);
			$value =$this->_pluralName($table);
			$arrayTables[$value]=$singular;
		} 
		
		if (empty($arrayTables)) {			 
			$this->Session->setFlash(__('Your database does not have any tables'));	
			$this->log(__('Your database does not have any tables',true), LOG_DEBUG);		
		 	//$this->redirect(array('action' => 'admin_index'));	
		 	return false;		 
		}
				
		$count = count($arrayTables);
		if ($count > 0){ 
			 $this->set('selectTables', $arrayTables); 	
			 
		} 
		return true; 
	}
	
	function __getModelsBd()
	{
		$useTable = null;
		
		$useDbConfig = $this->userDbConfig;
		$configs = get_class_vars('DATABASE_CONFIG');

		if (!is_array($configs)) {
			return $this->DbConfig->execute();
		}
		
		$tables=$this->listAll($useDbConfig);
		if (count($tables)> 0)	$this->set('tables', $tables); 			
		else					$this->set('tables', ""); 	
	}	
	
   
	
	/* Return a Array with each tables that have a model created */
	function __tables_with_model($tables)
	{	$out= array();
		$nTables=count($tables);
		$config_Modeldir=$this->viewVars["configuration"]["directory"].DS."app".DS."models".DS;
	 	foreach($tables as $table)
	 	{
	 		if(file_exists($config_Modeldir.$this->_singularName($table).".php"))
	 			$out[]=$table;	
	 	}
	 	return $out;
	}

	/* Return a Array with each tables than have not a model created */
	function __tables_without_model($tables)
	{	$out= array();
		$nTables=count($tables);
		$config_Modeldir=$this->viewVars["configuration"]["directory"].DS."app".DS."models".DS;
	 	foreach($tables as $table)
	 	{
	 		if(!file_exists($config_Modeldir.$this->_singularName($table).".php"))
	 			$out[]=$table;	
	 	}
	 	return $out;
	}	
	
	
	/* return path for controllers */
	function __getPath(){	
	     $session = $this->Session->read(KT_SESSION);	      
		 $path = $session[KT_CONFIGURATION][KT_DIRECTORY]."/app/controllers".DS; 
		 return $path;
	}
	   
}
?>